package com.use.userms2;
// FileName : 信息发布系统
// Author   : stcaaa@163.com
// DateTime : 2022/1/26 16:59
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText etName;
    private EditText etPhone;
    private TextView tvUsers;
    private TextView etInfo;
    SQLiteDatabase db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btnAdd).setOnClickListener(this);
        findViewById(R.id.btList).setOnClickListener(this);

        tvUsers=findViewById(R.id.tvUsers);
        etName=findViewById(R.id.etName);
        etPhone=findViewById(R.id.etPhone);
        etInfo=findViewById(R.id.tvInfo);
        //创建数据库及表
        db=openOrCreateDatabase("TestDB", Context.MODE_PRIVATE,null);
        String sql="CREATE TABLE IF NOT EXISTS user (\n" +
                "    id    INTEGER      PRIMARY KEY AUTOINCREMENT,\n" +
                "    name  VARCHAR (20),\n" +
                "    phone VARCHAR (20) \n" +
                ");";
        db.execSQL(sql);
        //更新显示用户表信息
        updateUserView();
    }

    @Override
    public void finish() {
        super.finish();
        db.close();
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.btnAdd){
            System.out.println("add ------------ok");
            addUser(etName.getText().toString(),etPhone.getText().toString());
            updateUserView();
        }
        if(v.getId()==R.id.btList){
            System.out.println("list ------------ok");
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, ListActivity.class);
            startActivity(intent);
        }

    }
    public void addUser(String name,String phone){

        ContentValues cv=new ContentValues(2);
        cv.put("name",name);
        cv.put("phone",phone);
        db.insert("user",null,cv);
    }
    public void updateUserView()
    {
        Cursor cur=db.rawQuery("select * from user",null);
        int sum=cur.getCount();
        String sUser=String.format("共有记录数量：%d \n",sum);
//        for(int i=0;i<sum;i++)
//        {
//            cur.moveToPosition(i);
//            sUser+=String.format("%s,%s\n",cur.getString(0),cur.getString(1));
//        }
        etInfo.setText(sUser);
    }
}

